package com.mydemo.likedy.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mydemo.likedy.Service.video.TypeService;
import com.mydemo.likedy.Utils.Result;

import com.mydemo.likedy.authority.Authority;
import com.mydemo.likedy.pojo.entity.video.Type;
import com.mydemo.likedy.pojo.vo.BasePage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 视频分类管理
 */
@RestController
@RequestMapping("/admin/type")
public class AdminTypeController {

    @Autowired
    private TypeService typeService;


    @GetMapping("/{id}")
    @Authority("admin:type:get")
    public Result get(@PathVariable Long id){
        return Result.success(typeService.getById(id));
    }


    @GetMapping("/page")
    @Authority("admin:type:page")
    public Result page(BasePage basePage){
        final IPage page = typeService.page(basePage.page(), null);
        return Result.success(page.getRecords(),page.getRecords().size());
    }

    @PostMapping
    @Authority("admin:type:add")
    public Result<Object> add(@RequestBody @Validated Type type){
        final int count = (int) typeService.count(new LambdaQueryWrapper<Type>().eq(Type::getName, type.getName()).ne(Type::getId,type.getId()));
        if (count == 1) return Result.success("分类已存在");
        typeService.save(type);
        return Result.success("添加成功");
    }

    @PutMapping
    @Authority("admin:type:update")
    public Result<Object> update(@RequestBody @Validated Type type){
        final int count = (int) typeService.count(new LambdaQueryWrapper<Type>().eq(Type::getName, type.getName()).ne(Type::getId,type.getId()));
        if (count == 1) return  Result.error("分类已存在");
        typeService.updateById(type);
        return Result.success("修改成功");
    }

    @DeleteMapping("/{id}")
    @Authority("admin:type:delete")
    public Result<Object> delete(@PathVariable Long id){
        typeService.removeById(id);
        return Result.success("删除成功");
    }

}
